package com.szx.usercenter.handle;

import cn.hutool.core.util.StrUtil;
import com.szx.usercenter.contance.BaseUser;
import com.szx.usercenter.util.JwtHelper;
import com.szx.usercenter.util.ResponseEnum;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author songzx
 * @date 2024/5/12
 * @apiNote
 */
public class TokenHandle implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 获取请求来源
        String referer = request.getHeader("Referer");

        boolean fromSwagger = referer.endsWith("swagger-ui/index.html");

        // 校验token
        if (!fromSwagger && (StrUtil.isEmpty(token) || JwtHelper.tokenExpired(token))) {
            throw new CenterExceptionHandler(ResponseEnum.LOGIN_EXPIRED);
        }

        // 获取用户名
        BaseUser.userName = JwtHelper.getUserName(token);
        return true;
    }
}
